#!/usr/bin/env python

import sys
import redi_utils as utils
import redi_messages as please

try: import json #python 2.6 included simplejson as json
except ImportError: import simplejson as json

def extract(filename):
    rfile = open(filename)

    wfile = open("extracted_" + utils.get_filename(filename), "w")
    wfile.write("GENE_ID\tFEATURE_TYPE\tDB_VERSION\tGENE_LOCUS\tCHROMOSOME\tSTART\tEND\tSTRAND\n")

    for line in rfile.readlines():
        linesplit = line.rstrip().split("\t")
        featureID = linesplit[1]
        featureType = linesplit[2]
        featureDBVersion = linesplit[7]
        geneLocus = linesplit[16]

        if "|" in featureID: featureID = featureID.split("|")[0]
        if ";" in geneLocus: geneLocus = geneLocus.split(";")[0]

        chrlocparts = geneLocus.split(":")
        chr = chrlocparts[0]
        start = chrlocparts[1].split("-")[0]
        end = chrlocparts[1].split("-")[1]
        strand = chrlocparts[2]

        if featureType == "gene":
            wfile.write("%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n"%(featureID,featureType,featureDBVersion,geneLocus,chr,start,end,strand))

if __name__ == "__main__":
    if len(sys.argv) > 1 and not sys.argv[1] is None:
        filename = sys.argv[1]
        extract(filename)
        exit(0)

    please.say("What am I supposed to do?  Guess?", "Try this instead...", "\tpython extractor_gaf.py FILENAME!")
